import app, { xlsxCfgNames } from "../../../app";
import god from "../../../god";
import { bag } from "../../../model/bag/bag";
import { prop_base } from "../../../model/bag/prop_base";
import db from "../../../model/db/db";
import { player } from "../../../model/fight/body/player";
import { logger } from "../../../model/server/logger";
import { bar, rank_type } from "../../../shared/interface";
import manage_user from "../manage/manage_user";
interface member_info {
    name:string
    uuid: string
    leve: number
    contribute: number
    /**
     * 累计贡献
     */
    contribute_accumulate: number
}
export class team {
    name: string = '未知';
    id: string = app.v4();
    desc: string = '未知小队描述';
    leve: bar = {
        num: 1,
        now: 0,
        max: 100
    }
    // 成员列表
    private memberlist: member_info[] = [];
    _onlineMap: Map<string, number> = new Map();
    _memberMap: Map<string, member_info> = new Map();
    score: number = 0;
    constructor(data: any) {
        for (const key in data) {
            const element = data[key];
            if (element) {
                this[key] = element;
            }
        }
        // 将 memberlist 转换为 _memberMap
        for (const member of this.memberlist) {
            this._memberMap.set(member.uuid, member);
        }
        setInterval(() => {
            this.updateOnline()
        }, 1000 * 60 * 5)
    }
    tick(body: player) {
        this._onlineMap.set(body.uuid, Date.now());
    }
    grantGift() {
        // 评分 / 人数 = 实际奖励评分
        let list = [...this._memberMap.values()]
        for (let i = 0; i < list.length; i++) {
            const element = list[i];
            let needValue = this.leve.num * 100 + this.leve.num * element.contribute;
            let _list = god.getRandomItems(needValue,`${this.name}补给`,xlsxCfgNames.商店配置)
            if(element.leve == 1){
                _list.push(app.createCfgItem(this.id, 0, `队长特权`));
            }
            god.send(
                { uuid: `${app.v4()}`, name: `${this.name}` },
                element.uuid,
                `${this.name}补给发放`,
                `作为${this.name}一份子,以下为当日小队战利品`,
                _list
            );
            element.contribute = 0;
            this.updateInfo(element)
        }
        this.save();
    }
    selectCaptain() {
        // 选择累计贡献最高者为小队队长
        /**
         * 1 贡献排序
         * 2 找到原队长ID
         * 3 选新队长
         * 4 如果id一样则发邮件给所有人续任
         * 5 如果不一样 则发邮件给所有人通知换队
         */
        let list = [...this._memberMap.values()]
        let contributeList = list.sort((a, b) => {
            return b.contribute_accumulate - a.contribute_accumulate;
        });
        let nextLeader = contributeList[0];
        let lastLeader = list.find((item) => {
            return item.leve == 1;
        });
        if (!nextLeader) {
            return;
        }

        if (lastLeader) {
            if (nextLeader.uuid != lastLeader.uuid) {
                // 通知原队长降级
                nextLeader.leve = 0;
                this.updateInfo(lastLeader)
            }else{
                god.send(
                    { uuid: `${app.v4()}`, name: `${this.name}` },
                    nextLeader.uuid,
                    `${this.name}队长选拔`,
                    `由于您出色的表现,故将续任队长一职.`,
                    []
                );
                logger.debug('队长续任')
                return;
            }
        }
        // 通知新队长上任
        nextLeader.leve = 1;
        this.updateInfo(nextLeader)
        // 通知全部成员
        for (let i = 0; i < list.length; i++) {
            const element = list[i];
            god.send(
                { uuid: `${app.v4()}`, name: `${this.name}` },
                element.uuid,
                `${this.name}队长选拔`,
                `${nextLeader.name}已成为${this.name}队长.\n队长ID${nextLeader.uuid}`,
                []
            );
        }

    }
    private updateInfo(info: member_info) {
        this._memberMap.set(info.uuid, info);
    }
    private updateOnline() {
        this._onlineMap.forEach((element, key) => {
            let data = manage_user.locaHas(key);
            if (!data) {
                this._onlineMap.delete(key);
            }
        });
    }
    get_onlineCont() {
        return this._onlineMap.size
    }
    getMember(uuid: string) {
        return this._memberMap.get(uuid);
    }
    addExp(body: player, num: number) {
        app.leveAddExp(num / 1000, this.leve, this.upLeve);
        let nowContribute = this.change_contribute(body.uuid, num / 1000)

        if (nowContribute) {
            body.rankLog(rank_type.小队贡献,nowContribute.contribute_accumulate,this.name)
        }

    }
    get_contribute(uuid: string) {
        let info = this._memberMap.get(uuid);
        if (!info) {
            debugger;
            return 0;
        }
        return info.contribute
    }
    change_contribute(uuid: string, change: number) {
        let info = this._memberMap.get(uuid);
        if (!info) {
            debugger;
            return;
        }
        info.contribute += change;
        if (change > 0) {
            info.contribute_accumulate += change;
        }
        this._memberMap.set(uuid, info);
        return info
    }
    private upLeve = () => {
        this.leve.num += 1;
        this.leve.max = this.leve.num * 1000000;
    }
    join(body: player) {
        body.team_id = this.id;
        const newMember = { uuid: body.uuid, leve: 0, contribute: 0, contribute_accumulate: 0,name:body.nickName };
        this._memberMap.set(body.uuid, newMember)


        body.update_team();
    }
    out(uuid: string) {
        this._memberMap.delete(uuid);
    }
    async save() {
        this.memberlist = [...this._memberMap.values()]
        let obj = app.sanitizeObject(this);
        const sql = `INSERT INTO team (id, data)
        VALUES (?, ?)
        ON DUPLICATE KEY UPDATE
        id = VALUES(id),
        data = VALUES(data)`;
        await db.sql(sql, [this.id, JSON.stringify(obj)])
    }
}